/*
 *    Copyright (c) 2018-2025, envpro All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: envpro
 */
package com.iwomy.envpro.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.iwomy.envpro.admin.api.dto.SysTenantDTO;
import com.iwomy.envpro.admin.api.entity.*;
import com.iwomy.envpro.admin.api.vo.RoleExcelVO;
import com.iwomy.envpro.admin.api.vo.SysTenantVo;
import com.iwomy.envpro.admin.config.ClientDetailsInitRunner;
import com.iwomy.envpro.admin.mapper.SysMenuMapper;
import com.iwomy.envpro.admin.mapper.SysRoleMenuMapper;
import com.iwomy.envpro.admin.mapper.SysSetMealDetailMapper;
import com.iwomy.envpro.admin.mapper.SysTenantMapper;
import com.iwomy.envpro.admin.service.*;
import com.iwomy.envpro.admin.utils.RedisClient;
import com.iwomy.envpro.app.api.entity.AppUser;
import com.iwomy.envpro.common.core.constant.CacheConstants;
import com.iwomy.envpro.common.core.constant.CommonConstants;
import com.iwomy.envpro.common.core.constant.SecurityConstants;
import com.iwomy.envpro.common.core.util.R;
import com.iwomy.envpro.common.core.util.SpringContextHolder;
import com.iwomy.envpro.common.data.datascope.DataScopeTypeEnum;
import com.iwomy.envpro.common.data.resolver.ParamResolver;
import com.iwomy.envpro.common.data.tenant.TenantBroker;
import com.iwomy.envpro.common.data.tenant.TenantContextHolder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 租户
 * <p>
 * mybatis-plus 3.4.3.3 特殊处理 https://github.com/baomidou/mybatis-plus/pull/3592
 *
 * @author envpro
 * @date 2019-05-15 15:55:41
 */
@Service
@AllArgsConstructor
@Slf4j
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements SysTenantService {

	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

	private final SysOauthClientDetailsService clientServices;

	private final SysUserRoleService userRoleService;

	private final SysRoleMenuMapper roleMenuMapper;

	private final SysDictItemService dictItemService;

	private final SysPublicParamService paramService;

	private final SysUserService userService;

	private final SysRoleService roleService;

	private final SysMenuService menuService;

	private final SysDeptService deptService;

	private final SysDictService dictService;

	private final SysTenantMenuService sysTenantMenuService;

	private final RedisClient redisClient;

	private final SysSetMealDetailMapper sysSetMealDetailMapper;

	/**
	 * 获取正常状态租户
	 * <p>
	 * 1. 状态正常 2. 开始时间小于等于当前时间 3. 结束时间大于等于当前时间
	 *
	 * @return
	 */
	@Override
	@Cacheable(value = CacheConstants.TENANT_DETAILS)
	public List<SysTenant> getNormalTenant() {
		return baseMapper
				.selectList(Wrappers.<SysTenant>lambdaQuery().eq(SysTenant::getStatus, CommonConstants.STATUS_NORMAL));
	}

	/**
	 * 保存租户
	 * <p>
	 * 1. 保存租户 2. 初始化权限相关表 - sys_user - sys_role - sys_menu - sys_user_role -
	 * sys_role_menu - sys_dict - sys_dict_item - sys_client_details - sys_public_params
	 *
	 * @param sysTenantDTO 租户实体
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(value = CacheConstants.TENANT_DETAILS)
	public Boolean saveTenant(SysTenantDTO sysTenantDTO) throws Exception {
		sysTenantDTO.setUsername(sysTenantDTO.getPhone());
		long l = userService.selectUserCountByUsername(sysTenantDTO.getUsername());
		if (l > 0) throw new Exception("用户名已存在");


		SysTenant sysTenant = BeanUtil.copyProperties(sysTenantDTO, SysTenant.class);
		sysTenant.setUsedUsers(1);
		sysTenant.setUsedVoice(0);
		sysTenant.setUsedSms(0);
		sysTenant.setUsedDevice(0);
		this.save(sysTenant);
		// 查询系统默认租户配置参数
		Long defaultId = ParamResolver.getLong("TENANT_DEFAULT_ID", 1L);
//		String defaultDeptName = ParamResolver.getStr("TENANT_DEFAULT_DEPTNAME", sysTenant.getName());
		String defaultDeptName = sysTenant.getName();
		String defaultUsername = ParamResolver.getStr("TENANT_DEFAULT_USERNAME", "admin");
		String defaultPassword = ParamResolver.getStr("TENANT_DEFAULT_PASSWORD", "Empaer");
		String defaultRoleCode = ParamResolver.getStr("TENANT_DEFAULT_ROLECODE", "ROLE_ADMIN");
		String defaultRoleName = ParamResolver.getStr("TENANT_DEFAULT_ROLENAME", "租户默认角色");
		String userDefaultRoleCode = ParamResolver.getStr("USER_DEFAULT_ROLECODE", "GENERAL_USER");
		String userDefaultRoleName = ParamResolver.getStr("USER_DEFAULT_ROLENAME", "普通用户");

		List<SysDict> dictList = new ArrayList<>(32);
		List<Long> dictIdList = new ArrayList<>(32);
		List<SysDictItem> dictItemList = new ArrayList<>(64);
		List<SysMenu> menuList = new ArrayList<>(128);
		List<SysOauthClientDetails> clientDetailsList = new ArrayList<>(16);
		List<SysPublicParam> publicParamList = new ArrayList<>(64);


		TenantBroker.runAs(defaultId, (id) -> {
			// 查询系统内置字典
			dictList.addAll(dictService.list());
			// 查询系统内置字典项目
			dictIdList.addAll(dictList.stream().map(SysDict::getId).collect(Collectors.toList()));
			dictItemList.addAll(
					dictItemService.list(Wrappers.<SysDictItem>lambdaQuery().in(SysDictItem::getDictId, dictIdList)));
			SysTenantMenu tenantMenu = sysTenantMenuService.getById(sysTenant.getMenuId());
			String[] split = tenantMenu.getMenuIds().split(",");
			List<SysMenu> newMenuList = menuService.list(Wrappers.<SysMenu>lambdaQuery().in(SysMenu::getMenuId, split));
			// 查询当前租户菜单
			menuList.addAll(newMenuList);
			// 查询客户端配置
			clientDetailsList.addAll(clientServices.list());
			// 查询系统参数配置
			publicParamList.addAll(paramService.list());
		});

		// 保证插入租户为新的租户
		TenantBroker.applyAs(sysTenant.getId(), (id -> {
			// 插入部门
			SysDept dept = new SysDept();
			dept.setName(defaultDeptName);
			dept.setParentId(0L);
			deptService.save(dept);
			// 构造初始化用户
			SysUser user = new SysUser();
			user.setUsername(sysTenantDTO.getUsername());
			user.setPassword(ENCODER.encode(defaultPassword));
			user.setDeptId(dept.getDeptId());
			user.setDefaultAccount(20);
			user.setUsername(sysTenantDTO.getPhone());
			user.setPhone(sysTenantDTO.getPhone());
			userService.save(user);

			// 构造普通用户角色
//			SysRole roleDefault = new SysRole();
//			roleDefault.setRoleCode(userDefaultRoleCode);
//			roleDefault.setRoleName(userDefaultRoleName);
//			roleDefault.setDsType(DataScopeTypeEnum.OWN_LEVEL.getType());
//			roleDefault.setDeptId(dept.getDeptId());
//			roleService.save(roleDefault);

			// 构造新角色 管理员角色
			SysRole role = new SysRole();
			role.setRoleCode(defaultRoleCode);
			role.setRoleName(defaultRoleName);
			role.setDsType(DataScopeTypeEnum.OWN_CHILD_LEVEL.getType());
			roleService.save(role);
			// 用户角色关系
			SysUserRole userRole = new SysUserRole();
			userRole.setUserId(user.getUserId());
			userRole.setRoleId(role.getRoleId());
			userRoleService.save(userRole);
			// 插入新的菜单
//			saveTenantMenu(menuList, CommonConstants.MENU_TREE_ROOT_ID, CommonConstants.MENU_TREE_ROOT_ID);

			// 重新查询出所有的菜单关联角色
//			List<SysMenu> list = menuService.list();

			// 查询全部菜单,构造角色菜单关系
			List<SysRoleMenu> roleMenuList = menuList.stream().map(menu -> {
				SysRoleMenu roleMenu = new SysRoleMenu();
				roleMenu.setRoleId(role.getRoleId());
				roleMenu.setMenuId(menu.getMenuId());
				return roleMenu;
			}).collect(Collectors.toList());
			roleMenuList.forEach(roleMenuMapper::insert);
			// 插入系统字典
			dictService.saveBatch(dictList.stream().peek(d -> d.setId(null)).collect(Collectors.toList()));
			// 处理字典项最新关联的字典ID
			List<SysDictItem> itemList = dictList.stream().flatMap(dict -> dictItemList.stream()
					.filter(item -> item.getDictType().equals(dict.getDictType())).peek(item -> {
						item.setDictId(dict.getId());
						item.setId(null);
					})).collect(Collectors.toList());

			// 插入客户端
			clientServices.saveBatch(clientDetailsList.stream().peek(d -> d.setId(null)).collect(Collectors.toList()));
			// 插入系统配置
			paramService
					.saveBatch(publicParamList.stream().peek(d -> d.setPublicId(null)).collect(Collectors.toList()));
			return dictItemService.saveBatch(itemList);
		}));

		SpringContextHolder.publishEvent(new ClientDetailsInitRunner.ClientDetailsInitEvent(sysTenant));

		return Boolean.TRUE;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean updateTenant(SysTenant newSysTenant) {
		Long tenantId = newSysTenant.getId();
		TenantContextHolder.setTenantSkip();
		SysTenant oldSysTenant = this.getById(newSysTenant.getId());

		if (oldSysTenant.getMenuId().equals(newSysTenant.getMenuId())) {
			return this.updateById(newSysTenant);
		}
		List<SysSetMealDetail> newSetMealDetails = sysSetMealDetailMapper
				.selectList(Wrappers.<SysSetMealDetail>lambdaQuery()
						.eq(SysSetMealDetail::getSetMealId, newSysTenant.getMenuId()));
		List<SysSetMealDetail> oldSetMealDetails = sysSetMealDetailMapper
				.selectList(Wrappers.<SysSetMealDetail>lambdaQuery()
						.eq(SysSetMealDetail::getSetMealId, oldSysTenant.getMenuId()));

		List<Long> newMenuIdList = newSetMealDetails.stream()
				.map(SysSetMealDetail::getMenuId).collect(Collectors.toList());
		List<Long> oldMenuIdList = oldSetMealDetails.stream()
				.map(SysSetMealDetail::getMenuId).collect(Collectors.toList());


		List<Long> tempList = BeanUtil.copyToList(oldMenuIdList, Long.class);

		//需要删除的
		oldMenuIdList.removeAll(newMenuIdList);
		List<Long> removedObjects = oldMenuIdList;
		if (ObjectUtil.isNotEmpty(removedObjects)) {
			LambdaQueryWrapper<SysSetMealDetail> deleteQW = Wrappers.<SysSetMealDetail>lambdaQuery()
					.eq(SysSetMealDetail::getSetMealId, tenantId)
					.in(SysSetMealDetail::getMenuId, removedObjects);
			sysSetMealDetailMapper.delete(deleteQW);
		}


		//需要新增的
		newMenuIdList.removeAll(tempList);
		List<Long> addedObjects = newMenuIdList;
		TenantContextHolder.setTenantId(tenantId);
		//查询所有角色
		if (ObjectUtil.isNotEmpty(removedObjects)) {
			List<SysRole> list = roleService.list();
			//删除所有角色的菜单
			list.stream().forEach(x -> {
				roleMenuMapper.delete(Wrappers.<SysRoleMenu>lambdaQuery()
						.eq(SysRoleMenu::getRoleId, x.getRoleId()).in(SysRoleMenu::getMenuId, removedObjects));
			});
		}
		if (ObjectUtil.isNotEmpty(addedObjects)) {
			//给admin新增
			List<RoleExcelVO> roleExcelVOS = roleService.adminRole();
			roleExcelVOS.forEach(x -> {
				SysRoleMenu sysRoleMenu = new SysRoleMenu();
				sysRoleMenu.setRoleId(x.getRoleId());
				addedObjects.stream().forEach(y -> {
					sysRoleMenu.setMenuId(y);
					try {
						roleMenuMapper.insert(sysRoleMenu);
					} catch (Exception e) {
						//插入异常显不处理
					}
				});
			});
		}
		Set<String> strings = redisClient.listKeyByPrefix(tenantId.toString());
		strings.forEach(redisClient::del);
		TenantContextHolder.setTenantId(tenantId);

		return this.updateById(newSysTenant);
	}

	@Override
	public Page getSysTenantPage(Page page, SysTenant sysTenant) {
		//多表查询
		MPJLambdaWrapper<SysTenant> wrapper = new MPJLambdaWrapper<>();
		wrapper.selectAll(SysTenant.class)
				.selectAs(SysTenantMenu::getName, SysTenantVo::getMenuName)
				.leftJoin(SysTenantMenu.class, SysTenantMenu::getId, SysTenant::getMenuId)
				.like(StrUtil.isNotBlank(sysTenant.getName()), SysTenant::getName, sysTenant.getName())
		;
		return this.getBaseMapper().selectJoinPage(page, SysTenantVo.class, wrapper);
	}

	@Override
	public List<SysTenant> getListByUsername(String username) {
		TenantContextHolder.clear();
		SysUser sysUser = new SysUser();
		sysUser.setUsername(username);
		LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery(sysUser);
		List<SysUser> list = userService.list(wrapper);
		List<Long> collect = list.stream().map(SysUser::getTenantId).collect(Collectors.toList());
		if (ObjectUtil.isEmpty(collect)) return new ArrayList<>();
		return this.listByIds(collect);
	}

	@Override
	public List<SysTenant> getTenants(String username, Integer type) {
		TenantContextHolder.clear();
		SysUser user = new SysUser();
		user.setUsername(username);
		LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery(user);
		List<SysUser> sysUsers = userService.list(wrapper);
		if (ObjectUtil.isEmpty(sysUsers)) return new ArrayList();
		List<Long> collect = sysUsers.stream().map(SysUser::getTenantId).collect(Collectors.toList());
		List<SysTenant> list = this.listByIds(collect).stream().filter(x -> "0".equals(x.getStatus())).collect(Collectors.toList());
		//pc端用户
		if (type == 0) return list;

		List<SysTenant> collect1 = list.stream().filter(x -> ObjectUtil.isNotNull(x.getMobileTerminal())
				&& collect.contains(x.getId())
				&& x.getMobileTerminal().contains(type.toString())).collect(Collectors.toList());
		return collect1;
	}

}
